package com.zqweb.gulimall.ssoserver.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

@Controller
@Slf4j
public class LoginController {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    // 根据登陆后得到的token，去Redis中获取到关联的UserInfo，然后响应回客户端
    @GetMapping("/getSessionUserInfo")
    @ResponseBody
    public String getSessionUserInfo(@RequestParam("token") String token){
        String userInfo = stringRedisTemplate.opsForValue().get(token);
        return userInfo;
    }

    // 接收用户登录请求，跳转到登录页面
    @GetMapping("/login")
    public String login(@RequestParam("redirect_url") String redirectUrl, Model model,
                        @CookieValue(name = "sso_token",required = false) String sso_token){
        // 接收登录请求参数：redirect_url，用于标识登录成功后重新跳转回因未登录被拦截的请求处
        if(!StringUtils.isEmpty(sso_token)){
            return "redirect:" + redirectUrl + "?token=" + sso_token;
        }else{
            model.addAttribute("reUrl",redirectUrl);
            return "Login";
        }
    }

    // 处理用户提交的登陆表单
    @PostMapping("/doLogin")
    public String doLogin(HttpServletRequest request, HttpServletResponse response){
        String userName = request.getParameter("userName");
        String password = request.getParameter("password");
        String reUrl = request.getParameter("reUrl");
        if(!StringUtils.isEmpty(userName) && !StringUtils.isEmpty(password)){
            String uuid = UUID.randomUUID().toString().replace("-","");
            // 将用户的登陆信息存到Redis中
            stringRedisTemplate.opsForValue().set(uuid,userName);
            /*
             将uuid的信息，以cookie的形式存放在浏览器端，只要浏览器访问ssoserver.com，就会带上该cookie
             其他请求携带该cookie去访问后台相关接口后，就知道已经有站点登陆过了，此时就将cookie的uuid值带上
             重新回到redirect_uri，而不是展示登陆界面继续登陆（单点登陆）
              */
            response.addCookie(new Cookie("sso_token",uuid));
            return "redirect:" + reUrl + "?token=" + uuid;
        }else{
            log.error("登陆失败，请重新登陆...");
            return "redirect:http://ssoserver.com:8080/login";
        }

    }

}
